import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author : lizhifeng
 * @create 2022/8/17 10:18
 * @DESC 2022/8/17 10:18
 */


public class MemoryDb {

    private Map<TransactionId, Transaction> db = new HashMap<TransactionId, Transaction>();

    private MemoryDb() {
    }

    private static final MemoryDb instance = new MemoryDb();

    public static MemoryDb getInstance() {
        return instance;
    }


    public void addTransaction(byte[] hash, Transaction transaction) {
        addTransaction(new TransactionId(hash), transaction);
    }


    public Transaction getTransaction(TransactionId transactionId) {
        return db.get(transactionId);
    }


    public void addTransaction(TransactionId transactionId, Transaction transaction) {
        db.put(transactionId, transaction);
    }


    public void accept(Block block) {

        Header header = block.getHeader();

        List<TransactionId> transactionIdList = block.getTransactionIdList();
        for (TransactionId transactionId : transactionIdList) {

            Transaction transaction = Pool.getInstance().getTransaction(transactionId);
            if (transaction == null) {
                throw new Error("transaction 交易不应该为空");
            }

            String address = Address.convertPubKeyToAddress(transaction.getPubKey());

            // 更新preTransactions相应的output为花费状态
            List<Input> inputs = transaction.getInputs();
            if (inputs != null) {
                for (Input input : inputs) {
                    TransactionId inputKey = input.getTransactionId();
                    // 将第i个output更新为已花费状态
                    DoubleCostCheck.getInstance().markAsSpent(inputKey, address);
                }
            }

            transaction.setHeight(header.getHeight());
            transaction.setTime(header.getTime());

            addTransaction(transactionId, transaction);
        }

    }

}
